package com.ccys.cms.service.marketing.impl;


import com.ccys.cms.service.marketing.NewsWebService;
import com.ccys.common.third.aws.s3.S3Util;
import com.ccys.common.third.push.firebase.FireBaseUtil;
import com.ccys.common.third.push.huawei.HuaWeiPush;
import com.ccys.common.third.push.ios.IosNotificationUtil;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.marketing.NewsDTO;
import com.ccys.db.entity.TblNews;
import com.ccys.db.entity.TblNewsPolicyUpload;
import com.ccys.db.entity.TblPlan;
import com.ccys.db.entity.TblPlanBenefit;
import com.ccys.db.mapper.*;
import com.ccys.db.page.PageUtils;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.marketing.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;


/**
 * tbl_news管理
 */
@Service
@Slf4j
public class NewsWebServiceImpl extends BaseServiceImpl<TblNews> implements NewsWebService {

    @Autowired(required = false)
    private TblNewsMapper newsMapper;
    @Autowired(required = false)
    private TblPlanMapper planMapper;

    @Autowired(required = false)
    private TblPlanBenefitMapper planBenefitMapper;

    @Autowired(required = false)
    private TblNewsPolicyUploadMapper newsPolicyUploadMapper;
    @Autowired(required = false)
    private TblPlanBenefitMemberMapper planBenefitMemberMapper;
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Override
    public ResponseResult listObjectsCms(HttpServletRequest request, HttpServletResponse response, NewsDTO dto) {
        PageUtils.startPage(request);
        List<NewsWebVO> list = this.newsMapper.listObjectsCms(dto);
        PageInfo pageInfo = new PageInfo<>(list);
        return ResponseResult.success(pageInfo);
    }


    @Override
    public ResponseResult change(NewsDTO entity) {
        String countryIds = entity.getCountryIds();
        //根据benifit 选取接受的用户
        String planBenefitIds = entity.getPlanBenefitIds();
        if(StringUtil.isEmpty(countryIds)) {
            return ResponseResult.error("countryIds is not null");
        }
        if (StringUtils.isBlank(entity.getId())) {
            if(entity.getStatus() == null) {
                entity.setStatus(1);
            }
            // 新增
            this.saveEntity(entity);
        } else {
            // 编辑
            this.updateEntityById(entity);
            if(entity.getStatus() != null) {
                this.baseTblAuditTrailWebService.saveStatusLog(entity,entity.getStatus());
            }
        }
        if(entity.getTargetType() != null && entity.getTargetType() == 1) {
            String fileUploadPath = entity.getFileUploadPath();
            //前端直接传解析后的数据
            String data = fileUploadPath;
            //获取对应的plan Id
            Example example = new Example(TblPlan.class);
            example.createCriteria().andCondition("del_flag=0")
                .andCondition("policy_no in " + Kit.getWhereByIds(data));
            List<TblPlan> tblPlans = this.planMapper.selectByExample(example);
            List<TblNewsPolicyUpload> dataList = new ArrayList<>();
            for (String d: data.split(",")) {
                TblNewsPolicyUpload t = new TblNewsPolicyUpload();
                t.setNewsId(entity.getId());
                t.setPolno(d);
                Integer matched = 0;
                for (TblPlan p : tblPlans) {
                    if(d.equals(p.getPolicyNo())) {
                        matched = 1;
                    }
                }
                t.setMatched(matched);
                dataList.add(t);
            }
            if(dataList.size() > 0){
                // 删除新闻之前的关联upload
                TblNewsPolicyUpload deleteTblNewsPolicyUpload = new TblNewsPolicyUpload();
                deleteTblNewsPolicyUpload.setNewsId(entity.getId());
                this.newsPolicyUploadMapper.delete(deleteTblNewsPolicyUpload);
                this.newsPolicyUploadMapper.insertList(dataList);
            }
        }else{
            // 直接选择plan
            String targetPolicies = entity.getTargetPolicies();
            if(StringUtil.isNotEmpty(targetPolicies)) {
                TblPlanBenefit benefit = new TblPlanBenefit();
                benefit.setPlanId(Kit.getWhereByIds(targetPolicies));
                List<NewsBenefitWebVO> selectList = this.planBenefitMapper.getSelectList(benefit);
                if(selectList != null && !selectList.isEmpty()) {
                    for (NewsBenefitWebVO m : selectList) {
                        Object id = m.getId();
                        if(id != null) {
                            planBenefitIds = planBenefitIds +  id.toString() + ",";
                        }
                    }
                }
            }
        }
        if("0".equals(countryIds)) {
            countryIds = null;
        }else {
            countryIds = Kit.getWhereByIds(countryIds);
        }
        //找到符合条件的用户
        List<Map> memberIds = this.planBenefitMemberMapper.getMemberIdsByCountryIdAndPlanBenefitIds(countryIds,Kit.getWhereByIds(planBenefitIds));
        // TODO cloudFly 发送内容待确认
        String title = "test";
        String body = "test";
        String hideMsg = null;
        sendThirdNotice(memberIds,title,body,hideMsg);
        return ResponseResult.success();
    }

    private void sendThirdNotice(List<Map> memberIds,String title,String body,String hideMsg) {
        if(memberIds != null && !memberIds.isEmpty()) {
            List<String> token1List = new ArrayList<>();
            List<String> token2List = new ArrayList<>();
            List<String> token3List = new ArrayList<>();
            // 推送新闻给用户
            for (Map m : memberIds) {
                if("1".equals(m.get("deviceType").toString())) {
                    token1List.add(m.get("deviceId").toString());
                }else if("2".equals(m.get("deviceType").toString())) {
                    token2List.add(m.get("deviceId").toString());
                }else if("3".equals(m.get("deviceType").toString())) {
                    token3List.add(m.get("deviceId").toString());
                }
                token1List.add(m.get("deviceId").toString());

            }
            //异步处理三方推送业务
            CompletableFuture.runAsync(() -> {
                try {
                    if(token1List != null && token1List.size() > 0) {
                        IosNotificationUtil.push(token1List,title,body,true,null);
                    }
                    if(token2List != null && token2List.size() > 0) {
                        FireBaseUtil.pushMulti(token2List,title,body);
                    }
                    if(token3List != null && token3List.size() > 0) {
                        HuaWeiPush.pushToByToken(title,body,hideMsg,token3List);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("异步处理三方推送异常");
                }

            });

        }
    }

    @Override
    public ResponseResult delete(TblNews dto) {
        TblNews entity = new TblNews();
        entity.setId(dto.getId());
        entity.setDelFlag(1);
        this.updateEntityById(entity);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getDetail(HttpServletRequest request, HttpServletResponse response, NewsDTO dto) {
        NewsDetailWebVO newsDetailWebVO = this.newsMapper.getDetail(dto);
        return ResponseResult.success(newsDetailWebVO);
    }

    @Override
    public ResponseResult analysisFileBenifitData(HttpServletRequest request,NewsDTO dto,MultipartFile file) {
        AnalysisFileBenifitDataWebVO resultMap = new AnalysisFileBenifitDataWebVO();
        String data = Kit.analysisPolicyNumberFileData(file);
        resultMap.setData(data);
        resultMap.setNewsBenefitWebVOList(null);
        if (StringUtil.isEmpty(data)) {
            return ResponseResult.success();
        }
        //获取对应的plan Id
        Example example = new Example(TblPlan.class);
        		example.createCriteria().andCondition("del_flag=0")
                .andCondition("policy_no in " + Kit.getWhereByIds(data));
        List<TblPlan> tblPlans = this.planMapper.selectByExample(example);
        List<NewsBenefitWebVO> selectList = null;
        if(tblPlans == null || tblPlans.isEmpty()) {
            return ResponseResult.success(resultMap);
        }else{
            String planIds = "";
            for (TblPlan p : tblPlans) {
                planIds = planIds + p.getId() + ",";
            }
            TblPlanBenefit planBenefit = new TblPlanBenefit();
            planBenefit.setPlanId(Kit.getWhereByIds(planIds));
            selectList = this.planBenefitMapper.getSelectList(planBenefit);
        }

        resultMap.setNewsBenefitWebVOList(selectList);
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult listPlanSelectListWebVO(HttpServletRequest request, HttpServletResponse response, NewsDTO dto) {
        TblPlan tblPlan = new TblPlan();
        List<PlanSelectListWebVO> list = this.planMapper.listPlanSelect(tblPlan);
        return ResponseResult.success(list);
    }


}